{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "4346df9d-5676-495e-b8f9-6a16e24a2280",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/opt/conda/lib/python3.9/site-packages/scipy/__init__.py:146: UserWarning: A NumPy version >=1.16.5 and <1.23.0 is required for this version of SciPy (detected version 1.24.1\n",
      "  warnings.warn(f\"A NumPy version >={np_minversion} and <{np_maxversion}\"\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "读取所有图像，生成X和y\n",
      "读取图像: 100%:  ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ ▋ \n",
      "X.shape: (812, 1024)\n",
      "y.shape: (812,)\n",
      "\n",
      "对X处理,保留90%的变异性对应的维度\n",
      "已保存pca\n",
      "X的形状: (812, 117)\n",
      "y的形状: (812,)\n",
      "\n",
      "用随机森林模型得到的准确率为:0.51\n",
      "已保存随机森林模型\n",
      "已保存准确率\n"
     ]
    }
   ],
   "source": [
    "from sklearn.ensemble import RandomForestClassifier\n",
    "import matplotlib.pyplot as plt\n",
    "import cv2 as cv\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import pickle\n",
    "import os\n",
    "from os.path import exists\n",
    "from imutils import paths  # 使用这个\n",
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "from sklearn.model_selection import train_test_split\n",
    "import time\n",
    "import faiss\n",
    "from sklearn.decomposition import PCA\n",
    "import math\n",
    "# 显示进度条\n",
    "\n",
    "def progress_bar(s, i):\n",
    "    print(\"\\r\", end=\"\")  # 输出位置回到行首\n",
    "    print(s+\": {}%: \".format(i), \"▋ \" * (i // 2), end=\"\")\n",
    "\n",
    "print(\"读取所有图像，生成X和y\")\n",
    "l = list(paths.list_images('.'))  # 从当前文件夹中获得所有的图像文件列表\n",
    "X = []  # 数据信息\n",
    "y = []  # 标签信息\n",
    "c = 1\n",
    "for i in l:\n",
    "    progress_bar(\"读取图像\", c*100//len(l))\n",
    "    img = cv.imread(i, 0)  # 已灰度图读入\n",
    "    img = cv.resize(img, (32, 32))\n",
    "    X.append(img.ravel())\n",
    "    label = i.split(os.path.sep)[-1].split(\".\")[0]\n",
    "    y.append(label)\n",
    "    c = c+1\n",
    "print(\"\\nX.shape:\", np.shape(X))\n",
    "print(\"y.shape:\", np.shape(y))\n",
    "\n",
    "#1.得到X,y\n",
    "X = np.array(X)\n",
    "y = np.array(y)\n",
    "print('\\n对X处理,保留90%的变异性对应的维度')\n",
    "pca = PCA(0.9).fit(X)  # <--- 保留90%的变异性对应的维度\n",
    "X = pca.transform(X)\n",
    "with open('pca', 'wb') as f:\n",
    "    pickle.dump(pca, f)\n",
    "    print('已保存pca')\n",
    "print(\"X的形状:\", X.shape)\n",
    "print(\"y的形状:\", y.shape)\n",
    "\n",
    "# 2. train_test_split 划分数据集\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25)\n",
    "\n",
    "# 3. 训练 随机森林 模型\n",
    "clf = RandomForestClassifier()\n",
    "clf.fit(X_train, y_train)\n",
    "acc=clf.score(X_test,y_test)\n",
    "print('\\n用随机森林模型得到的准确率为:{:.2f}'.format(acc))\n",
    "with open(\"clf\", 'wb') as f:\n",
    "    pickle.dump(clf, f)\n",
    "    print(\"已保存随机森林模型\")\n",
    "with open(\"acc\", 'wb') as f:\n",
    "    pickle.dump(acc, f)\n",
    "    print(\"已保存准确率\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
